/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mail.web;

import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import mail.server.MailServer;

/**
 *
 * @author timoteo
 */
@Named
@RequestScoped
public class RegisterBean {

    private static final Logger logger = Logger.getLogger(RegisterBean.class.getName());
    private String username;
    @Inject
    private MailServer mailServer;
    @Inject
    private FacesContext context;

    public RegisterBean() {
    }

    public RegisterBean(MailServer mailServer, FacesContext context) {
        this.mailServer = mailServer;
        this.context = context;
    }

    public String registerUser() {
        if (username == null || username.isEmpty()) {
            context.addMessage(null, new FacesMessage("Invalid username : " + username));
            return "failed";
        } else if (mailServer.existsAccountInServer(username)) {
            context.addMessage(null, new FacesMessage("User already exists: " + username));
            return "failed";
        } else {
            mailServer.addAccountsServer(username);
            logger.info("User registered : " + username);
            context.addMessage(null, new FacesMessage("User registered : " + username));
        }
        return "success";
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
